/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.SwingWorker;

/**
 *
 * @author bob
 */
//test
//test
public class Apartment extends javax.swing.JFrame {

    /**
     * Creates new form Apartment
     */
    public Apartment() throws SQLException {
        initComponents();
        aptTable.setAutoCreateRowSorter(true);
        showAll();
    }
    
    private void showAll() throws SQLException
    {
        SwingWorker bgThread = new SwingWorker()
        {
            ResultSet rset;

            @Override
            protected Object doInBackground() throws Exception 
            {
                String  query = "SELECT * FROM APARTMENT WHERE NUM NOT IN (SELECT DISTINCT APTNO FROM TENANT)";
                DBconnection db = new DBconnection();
                Connection conn = db.getConnection();
                PreparedStatement statement = null;
                statement = conn.prepareStatement(query);

                ///////////////////////////////
                statement = conn.prepareStatement(query);        

                rset = statement.executeQuery();
                
                        throw new UnsupportedOperationException("Not supported yet.");
            }
            
             @Override
             protected void done() {
                try {
                    ListTableModel model = ListTableModel.createModelFromResultSet( rset ); 
                    aptTable.setModel(model);
                } catch (SQLException ex) {
                    Logger.getLogger(Apartment.class.getName()).log(Level.SEVERE, null, ex);
                }
             }
        };
        bgThread.execute();
        
   }
      
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        aptTable = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        priceBox = new javax.swing.JTextField();
        searchButton = new javax.swing.JButton();
        searchNumBox = new javax.swing.JTextField();
        setPriceButton = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        showButton = new javax.swing.JButton();
        jLabel8 = new javax.swing.JLabel();
        priceOrderBox = new javax.swing.JComboBox();
        jLabel9 = new javax.swing.JLabel();
        roomsDropBox = new javax.swing.JComboBox();
        jLabel10 = new javax.swing.JLabel();
        balconyDropBox = new javax.swing.JComboBox();
        jButton3 = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        aptTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null}
            },
            new String [] {
                "Apt Number", "Price", "Rooms", "Sq Feet", "Balcony"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(aptTable);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createTitledBorder(""), "Information", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 18))); // NOI18N

        jLabel1.setText("Price:");

        searchButton.setText("Search");
        searchButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                searchButtonMouseClicked(evt);
            }
        });

        setPriceButton.setText("Set Price");
        setPriceButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                setPriceButtonMouseClicked(evt);
            }
        });
        setPriceButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                setPriceButtonActionPerformed(evt);
            }
        });

        jLabel2.setText("Apartment Number:");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(42, 42, 42)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(priceBox, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(setPriceButton, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(searchButton)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(searchNumBox, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(655, 655, 655))))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap(27, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(searchButton)
                    .addComponent(searchNumBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addGap(26, 26, 26)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(priceBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(setPriceButton))
                .addGap(67, 67, 67))
        );

        jLabel1.getAccessibleContext().setAccessibleName("Tenant SSN:");

        showButton.setText("Show Apartments");
        showButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                showButtonMouseClicked(evt);
            }
        });
        showButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                showButtonActionPerformed(evt);
            }
        });

        jLabel8.setText("Price:");

        priceOrderBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Ascending", "Descending" }));

        jLabel9.setText("Rooms:");

        roomsDropBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Any", "1", "2", "3" }));

        jLabel10.setText("Balcony:");

        balconyDropBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Any", "Yes", "No" }));

        jButton3.setText("Back");
        jButton3.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton3MouseClicked(evt);
            }
        });

        jButton1.setText("Show All");
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton1MouseClicked(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(55, 55, 55)
                        .addComponent(showButton))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(45, 45, 45)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel9)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(roomsDropBox, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel10)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(balconyDropBox, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel8)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(priceOrderBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 24, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 712, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 393, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton3))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jButton1)))
                .addGap(29, 29, 29))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(28, 28, 28)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(showButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel8)
                            .addComponent(priceOrderBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel9)
                            .addComponent(roomsDropBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel10)
                            .addComponent(balconyDropBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(29, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton3)
                        .addContainerGap())))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void setPriceButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_setPriceButtonActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_setPriceButtonActionPerformed

    private void showButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_showButtonActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_showButtonActionPerformed

    private void jButton3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton3MouseClicked

        //create main window
        MainMenu main = new MainMenu();
        main.setLocation(MainMenu.X, MainMenu.Y);
        main.setVisible(true);
                
        //close this window
        this.dispose();  
    }//GEN-LAST:event_jButton3MouseClicked

    private void searchButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_searchButtonMouseClicked
        try {
            int num = Integer.parseInt(searchNumBox.getText());
            int rooms;
            int sqfeet;
            float price;
            char balcony;
            
            String query = "SELECT * FROM APARTMENT WHERE NUM = ?";
            DBconnection db = new DBconnection();
            Connection conn = db.getConnection();
            PreparedStatement statement = null;
            statement = conn.prepareStatement(query);
            ///////////////////////////////
            statement.setInt(1, num);

            ///////////////////////////////
            ResultSet rset = statement.executeQuery();


            ListTableModel model = ListTableModel.createModelFromResultSet( rset );
            aptTable.setModel(model); 
            statement.close();
        } catch (SQLException ex) {
            Logger.getLogger(Apartment.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_searchButtonMouseClicked

    private void showButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_showButtonMouseClicked
        try {
            int priceChoice = priceOrderBox.getSelectedIndex();
            int roomsChoice = roomsDropBox.getSelectedIndex();         
            int balconyChoice = balconyDropBox.getSelectedIndex();
            
            String query = " SELECT * FROM APARTMENT";
            DBconnection db = new DBconnection();
            Connection conn = db.getConnection();
            PreparedStatement statement = null;
            statement = conn.prepareStatement(query);
            
            
            if(roomsChoice != 0)
            {                
                query += " WHERE ROOMS = "+ roomsChoice;
                statement = conn.prepareStatement(query);
                //System.out.println(roomsChoice  );                
                //statement.setInt(1, roomsChoice);
            }
             
            if(balconyChoice != 0)
            {
                if(roomsChoice != 0)
                {
                    query += " AND ";
                }
                else
                {
                    query += " WHERE ";
                }
                if(balconyChoice == 1)
                {
                    query += " BALCONY = 'Y'";
                    statement = conn.prepareStatement(query);                              
                 
                }
                else if(balconyChoice == 2)
                {
                    query += " BALCONY = 'N'";
                    statement = conn.prepareStatement(query);   
                }
             
            }
            if(roomsChoice == 0)
            {
                query += " WHERE ";
            }
            else
            {
                query += " AND ";
            }
            
            query += "NUM NOT IN (SELECT DISTINCT APTNO FROM TENANT)";
            if(priceChoice == 0)
            {
                query += " ORDER BY PRICE";
                statement = conn.prepareStatement(query);
            }
            else
            {
                query += " ORDER BY PRICE DESC";
                statement = conn.prepareStatement(query);
            }
            System.out.println(query);
            ResultSet rset = statement.executeQuery();                      
                   
            ListTableModel model = ListTableModel.createModelFromResultSet( rset );
            aptTable.setModel(model); 
            statement.close();
        } catch (SQLException ex) {
            Logger.getLogger(Apartment.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_showButtonMouseClicked

    private void setPriceButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_setPriceButtonMouseClicked
          try {
            int num = Integer.parseInt(searchNumBox.getText());            
            float price = Float.parseFloat(priceBox.getText());
            
            
            String query = "UPDATE APARTMENT SET PRICE = ? WHERE NUM = ? ";
            DBconnection db = new DBconnection();
            Connection conn = db.getConnection();
            PreparedStatement statement = null;
            statement = conn.prepareStatement(query);
            ///////////////////////////////
            statement.setFloat(1, price);
            statement.setInt(2, num);
            statement.executeUpdate();
            statement.close();

            ///////////////////////////////
            query = "SELECT * FROM APARTMENT WHERE NUM = ?";
            statement = conn.prepareStatement(query);
            statement.setFloat(1, num);
            
            ResultSet rset = statement.executeQuery();


            ListTableModel model = ListTableModel.createModelFromResultSet( rset );
            aptTable.setModel(model); 
           
        } catch (SQLException ex) {
            Logger.getLogger(Apartment.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_setPriceButtonMouseClicked

    private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MouseClicked
         SwingWorker bgThread = new SwingWorker()
        {
            ResultSet rset;

            @Override
            protected Object doInBackground() throws Exception 
            {
                String  query = "SELECT * FROM APARTMENT";
                DBconnection db = new DBconnection();
                Connection conn = db.getConnection();
                PreparedStatement statement = null;
                statement = conn.prepareStatement(query);

                ///////////////////////////////
                statement = conn.prepareStatement(query);        

                rset = statement.executeQuery();
                
                        throw new UnsupportedOperationException("Not supported yet.");
            }
            
             @Override
             protected void done() {
                try {
                    ListTableModel model = ListTableModel.createModelFromResultSet( rset ); 
                    aptTable.setModel(model);
                } catch (SQLException ex) {
                    Logger.getLogger(Apartment.class.getName()).log(Level.SEVERE, null, ex);
                }
             }
        };
        bgThread.execute();
    }//GEN-LAST:event_jButton1MouseClicked

 
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTable aptTable;
    private javax.swing.JComboBox balconyDropBox;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField priceBox;
    private javax.swing.JComboBox priceOrderBox;
    private javax.swing.JComboBox roomsDropBox;
    private javax.swing.JButton searchButton;
    private javax.swing.JTextField searchNumBox;
    private javax.swing.JButton setPriceButton;
    private javax.swing.JButton showButton;
    // End of variables declaration//GEN-END:variables
}
